﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EPPLib.Data;
using EPPLib.Managers;
using EPPLib.Messages;

namespace EPPWebMVC.Controllers
{
    public class ContactController : BaseController
    {
        private const string DEFAULT_PREFIX = "+39";
        private const string DEFAULT_COUNTRY = "IT";

        [Authorize]
        public ActionResult Index()
        {
            ContactDataCollection contacts = Data.ReadContacts(CurrentUserID);
            SetBaseViewData();
            return View(contacts);
        }

        [Authorize]
        public ActionResult Details(int id)
        {
            SetBaseViewData();
            return View();
        }

        [Authorize]
        public ActionResult CreateRegistrant()
        {
            CountryDataCollection countries = Data.ReadCountries();
            EntityTypeDataCollection types = Data.ReadEntityTypes();

            ViewData["__COUNTRIES"] = new SelectList(countries, "Code", "Description", DEFAULT_COUNTRY);
            ViewData["__PHONE_PREFIXES"] = new SelectList(countries, "PhonePrefix", "PhonePrefix", DEFAULT_PREFIX);
            ViewData["__FAX_PREFIXES"] = new SelectList(countries, "PhonePrefix", "PhonePrefix", DEFAULT_PREFIX);
            ViewData["__ENTITY_TYPES"] = new SelectList(types, "Value", "Description");

            SetBaseViewData();
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult CreateRegistrant(ContactDataObject data)
        {
            data.OwnerID = CurrentUserID;

            CountryDataCollection countries = Data.ReadCountries();
            EntityTypeDataCollection types = Data.ReadEntityTypes();
            ViewData["__COUNTRIES"] = new SelectList(countries, "Code", "Description", data.CountryCode);
            ViewData["__PHONE_PREFIXES"] = new SelectList(countries, "PhonePrefix", "PhonePrefix", data.PhonePrefix);
            ViewData["__FAX_PREFIXES"] = new SelectList(countries, "PhonePrefix", "PhonePrefix", data.FaxPrefix);
            ViewData["__ENTITY_TYPES"] = new SelectList(types, "Value", "Description", data.EntityType);

            if (ModelState.IsValid)
            {
                if (!Service.IsAuthenticated)
                {
                    LoginMessage loginRequest = new LoginMessage();
                    loginRequest.RegistrarID = CurrentAccount;
                    loginRequest.Password = CurrentPassword;
                    LoginResponseMessage loginResponse = Service.Login(CurrentTargetUrl, loginRequest);
                    if (loginResponse.Response.Status == EPPLib.Objects.ResponseObject.ResponseStatus.Done)
                    {
                        Service.IsAuthenticated = true;
                    }
                    else
                    {
                        Service.IsAuthenticated = false;
                    }
                }

                CreateContactMessage contactMessage = new CreateContactMessage();
                contactMessage.ContactID = data.ID;
                contactMessage.PostalInfo.Name = data.Name;
                contactMessage.PostalInfo.Address.Address[0] = data.Street1;
                contactMessage.PostalInfo.Address.Address[1] = data.Street2;
                contactMessage.PostalInfo.Address.Address[2] = data.Street3;
                contactMessage.PostalInfo.Address.City = data.City;
                contactMessage.PostalInfo.Address.District = data.District;
                contactMessage.PostalInfo.Address.PostalCode = data.PostalCode;
                contactMessage.PostalInfo.Address.CountryCode = data.CountryCode;
                if (!string.IsNullOrEmpty(data.PhonePrefix) && !string.IsNullOrEmpty(data.Phone))
                {
                    contactMessage.Phone.Number = string.Format("{0}.{1}", data.PhonePrefix, data.Phone);
                    contactMessage.Phone.Internal = data.PhoneInternal;
                }
                if (!string.IsNullOrEmpty(data.FaxPrefix) && !string.IsNullOrEmpty(data.Fax))
                {
                    contactMessage.Fax.Number = string.Format("{0}.{1}", data.FaxPrefix, data.Fax);
                    contactMessage.Fax.Internal = data.FaxInternal;
                }
                contactMessage.Email = data.Email;
                contactMessage.AuthInfo.Password = data.AuthInfo;

                CreateExtendedContactMessage extendedContactMessage = new CreateExtendedContactMessage();
                extendedContactMessage.ConsentForPublishing = data.ConsentForPublishing;
                extendedContactMessage.Registrant.EntityType = data.EntityType;
                extendedContactMessage.Registrant.NationalityCode = data.NationalityCode;
                extendedContactMessage.Registrant.TaxCode = data.RegCode.ToLower();

                CreateContactResponseMessage responseMessage = Service.CreateContact(CurrentTargetUrl, CurrentAccount, CurrentPassword,
                    contactMessage,
                    extendedContactMessage,
                    MessageContainer.ComposeClientTransactionID(CurrentAccount, Data.IncreaseOperationCount(CurrentUserID)));

                if (responseMessage.Response.Status == EPPLib.Objects.ResponseObject.ResponseStatus.Done)
                {
                    Data.SaveContact(data);
                }

                SetBaseViewData(responseMessage);
            }
            else
            {
                SetBaseViewData();
            }
            return View();
        }


        [Authorize]
        public ActionResult CreateTechAdmin()
        {
            CountryDataCollection countries = Data.ReadCountries();
            EntityTypeDataCollection types = Data.ReadEntityTypes();

            ViewData["__COUNTRIES"] = new SelectList(countries, "Code", "Description", DEFAULT_COUNTRY);
            ViewData["__PHONE_PREFIXES"] = new SelectList(countries, "PhonePrefix", "PhonePrefix", DEFAULT_PREFIX);
            ViewData["__FAX_PREFIXES"] = new SelectList(countries, "PhonePrefix", "PhonePrefix", DEFAULT_PREFIX);
            ViewData["__ENTITY_TYPES"] = new SelectList(types, "Value", "Description");

            SetBaseViewData();
            return View();
        }
        [Authorize]
        [HttpPost]
        public ActionResult CreateTechAdmin(ContactDataObject data)
        {
            data.OwnerID = CurrentUserID;

            CountryDataCollection countries = Data.ReadCountries();
            EntityTypeDataCollection types = Data.ReadEntityTypes();
            ViewData["__COUNTRIES"] = new SelectList(countries, "Code", "Description", data.CountryCode);
            ViewData["__PHONE_PREFIXES"] = new SelectList(countries, "PhonePrefix", "PhonePrefix", data.PhonePrefix);
            ViewData["__FAX_PREFIXES"] = new SelectList(countries, "PhonePrefix", "PhonePrefix", data.FaxPrefix);
            ViewData["__ENTITY_TYPES"] = new SelectList(types, "Value", "Description", data.EntityType);

            if (ModelState.IsValid)
            {
                if (!Service.IsAuthenticated)
                {
                    LoginMessage loginRequest = new LoginMessage();
                    loginRequest.RegistrarID = CurrentAccount;
                    loginRequest.Password = CurrentPassword;
                    LoginResponseMessage loginResponse = Service.Login(CurrentTargetUrl, loginRequest);
                    if (loginResponse.Response.Status == EPPLib.Objects.ResponseObject.ResponseStatus.Done)
                    {
                        Service.IsAuthenticated = true;
                    }
                    else
                    {
                        Service.IsAuthenticated = false;
                    }
                }

                CreateContactMessage contactMessage = new CreateContactMessage();
                contactMessage.ContactID = data.ID;
                contactMessage.PostalInfo.Name = data.Name;
                contactMessage.PostalInfo.Address.Address[0] = data.Street1;
                contactMessage.PostalInfo.Address.Address[1] = data.Street2;
                contactMessage.PostalInfo.Address.Address[2] = data.Street3;
                contactMessage.PostalInfo.Address.City = data.City;
                contactMessage.PostalInfo.Address.District = data.District;
                contactMessage.PostalInfo.Address.PostalCode = data.PostalCode;
                contactMessage.PostalInfo.Address.CountryCode = data.CountryCode;
                if (!string.IsNullOrEmpty(data.PhonePrefix) && !string.IsNullOrEmpty(data.Phone))
                {
                    contactMessage.Phone.Number = string.Format("{0}.{1}", data.PhonePrefix, data.Phone);
                    contactMessage.Phone.Internal = data.PhoneInternal;
                }
                if (!string.IsNullOrEmpty(data.FaxPrefix) && !string.IsNullOrEmpty(data.Fax))
                {
                    contactMessage.Fax.Number = string.Format("{0}.{1}", data.FaxPrefix, data.Fax);
                    contactMessage.Fax.Internal = data.FaxInternal;
                }
                contactMessage.Email = data.Email;

                CreateExtendedContactMessage extendedContactMessage = new CreateExtendedContactMessage();

                CreateContactResponseMessage responseMessage = Service.CreateContact(CurrentTargetUrl, CurrentAccount, CurrentPassword,
                    contactMessage,
                    extendedContactMessage,
                    MessageContainer.ComposeClientTransactionID(CurrentAccount, Data.IncreaseOperationCount(CurrentUserID)));

                if (responseMessage.Response.Status == EPPLib.Objects.ResponseObject.ResponseStatus.Done)
                    Data.SaveContact(data);

                SetBaseViewData(responseMessage);
            }
            else
            {
                SetBaseViewData();
            }
            return View();
        }

        [Authorize]
        public ActionResult Edit(int id)
        {
            SetBaseViewData();
            return View();
        }

        //
        // POST: /Contact/Edit/5

        [Authorize]
        [HttpPost]
        public ActionResult Edit(int id, ContactDataObject data)
        {
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                SetBaseViewData();
                return View();
            }
        }

        [Authorize]
        public ActionResult Delete(string userID)
        {
            ViewData["__CONTACT_ID"] = userID;
            SetBaseViewData();
            return View();
        }
        [Authorize]
        [HttpPost]
        public ActionResult Delete(FormCollection data)
        {
            DeleteContactMessage message = new DeleteContactMessage();
            if (!string.IsNullOrEmpty(data["idBox"])) message.ID = data["idBox"];
            DeleteContactResponseMessage responseMessage = Service.DeleteContact(CurrentTargetUrl, CurrentAccount, CurrentPassword, message, MessageContainer.ComposeClientTransactionID(CurrentAccount, Data.IncreaseOperationCount(CurrentUserID)));
            if (responseMessage.Response.Status == EPPLib.Objects.ResponseObject.ResponseStatus.Done)
                Data.DeleteContact(data["idBox"], CurrentUserID);

            SetBaseViewData(responseMessage);
            return View();
        }

        [Authorize]
        public ActionResult Import()
        {
            SetBaseViewData();
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult Import(FormCollection data)
        {
            SetBaseViewData();
            return View();
        }

        [Authorize]
        public ActionResult Check()
        {
            SetBaseViewData();
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult Check(FormCollection data)
        {
            CheckContactMessage message = new CheckContactMessage();
            if (!string.IsNullOrEmpty(data["idBox1"])) message.IDs.Add(data["idBox1"]);
            if (!string.IsNullOrEmpty(data["idBox2"])) message.IDs.Add(data["idBox2"]);
            if (!string.IsNullOrEmpty(data["idBox3"])) message.IDs.Add(data["idBox3"]);
            if (!string.IsNullOrEmpty(data["idBox4"])) message.IDs.Add(data["idBox4"]);
            if (!string.IsNullOrEmpty(data["idBox5"])) message.IDs.Add(data["idBox5"]);

            CheckContactResponseMessage response = Service.CheckContact(CurrentTargetUrl, CurrentAccount, CurrentPassword, message, MessageContainer.ComposeClientTransactionID(CurrentAccount, Data.IncreaseOperationCount(CurrentUserID)));
            SetBaseViewData(response);
            return View();
        }

        [Authorize]
        public ActionResult Info(string userID)
        {
            ViewData["__CONTACT_ID"] = userID;
            SetBaseViewData();
            return View();
        }
        [Authorize]
        [HttpPost]
        public ActionResult Info(FormCollection data)
        {
            InfoContactMessage message = new InfoContactMessage();
            if (!string.IsNullOrEmpty(data["idBox"])) message.ID = data["idBox"];
            InfoContactResponseMessage responseMessage = Service.InfoContact(CurrentTargetUrl, CurrentAccount, CurrentPassword, message, MessageContainer.ComposeClientTransactionID(CurrentAccount, Data.IncreaseOperationCount(CurrentUserID)));
            if (responseMessage.Response.Status == EPPLib.Objects.ResponseObject.ResponseStatus.Done)
            {
                ContactDataObject contact = Data.ReadContact(data["idBox"], CurrentUserID);
                contact.NicID = responseMessage.Response.Data.InfoContact.NicID;
                contact.CurrentRegistrar = responseMessage.Response.Data.InfoContact.CurrentRegistrar;
                contact.CreateRegistrar = responseMessage.Response.Data.InfoContact.CreateRegistrar;
                contact.UpdateRegistrar = responseMessage.Response.Data.InfoContact.UpdateRegistrar;
                contact.CreateDate = responseMessage.Response.Data.InfoContact.CreateDate;
                contact.UpdateDate = responseMessage.Response.Data.InfoContact.UpdateDate;
                if (responseMessage.Response.Data.InfoContact.Status.Count > 0)
                    contact.Status1 = responseMessage.Response.Data.InfoContact.Status[0].Status;
                if (responseMessage.Response.Data.InfoContact.Status.Count > 1)
                    contact.Status2 = responseMessage.Response.Data.InfoContact.Status[1].Status;
                ContactDataObject test = Data.SaveContact(contact);
            }
            SetBaseViewData(responseMessage);
            return View();
        }
    }
}
